package com.salon.client.widgets;

import com.extjs.gxt.ui.client.Registry;
import com.extjs.gxt.ui.client.Style.HorizontalAlignment;
import com.extjs.gxt.ui.client.data.BaseListLoadResult;
import com.extjs.gxt.ui.client.data.BaseListLoader;
import com.extjs.gxt.ui.client.data.BeanModel;
import com.extjs.gxt.ui.client.data.BeanModelReader;
import com.extjs.gxt.ui.client.data.ListLoadResult;
import com.extjs.gxt.ui.client.data.LoadEvent;
import com.extjs.gxt.ui.client.data.RpcProxy;
import com.extjs.gxt.ui.client.event.ButtonEvent;
import com.extjs.gxt.ui.client.event.SelectionChangedEvent;
import com.extjs.gxt.ui.client.event.SelectionChangedListener;
import com.extjs.gxt.ui.client.event.SelectionListener;
import com.extjs.gxt.ui.client.store.ListStore;
import com.extjs.gxt.ui.client.util.IconHelper;
import com.extjs.gxt.ui.client.widget.Dialog;
import com.extjs.gxt.ui.client.widget.Info;
import com.extjs.gxt.ui.client.widget.button.Button;
import com.extjs.gxt.ui.client.widget.form.ComboBox;
import com.extjs.gxt.ui.client.widget.form.DateField;
import com.extjs.gxt.ui.client.widget.form.NumberField;
import com.extjs.gxt.ui.client.widget.form.TextField;
import com.extjs.gxt.ui.client.widget.form.ComboBox.TriggerAction;
import com.extjs.gxt.ui.client.widget.layout.FormLayout;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.salon.client.GreetingServiceAsync;
import com.salon.client.Salon;
import com.salon.client.beans.ClientBean;
import com.salon.client.beans.IncomeMaterialsBean;
import com.salon.client.beans.MasterBean;
import com.salon.client.beans.MaterialBean;
import com.salon.client.beans.ParentPagingLoadResult;
import com.salon.client.beans.PriceBean;
import com.salon.client.beans.ProcedureBean;
import com.salon.client.tabItems.IncomeTabItemPanel;
import com.salon.client.tabItems.ProcedureTabItemPanel;

public class ProcedureDialog extends Dialog {
	protected ComboBox<BeanModel> combo1 = new ComboBox<BeanModel>();
	protected ComboBox<BeanModel> combo2 = new ComboBox<BeanModel>();
	protected ComboBox<BeanModel> combo3 = new ComboBox<BeanModel>();
	protected DateField date = new DateField();
	protected TextField<String> desc = new TextField<String>();
	protected NumberField cost = new NumberField();
	
	protected ProcedureBean bean = new ProcedureBean();
	private ProcedureTabItemPanel parentPanel;
	
	
	public ProcedureDialog(ProcedureTabItemPanel panel) {
		parentPanel = panel;
		setHeading("Добавление товара");
		FormLayout layout = new FormLayout();
	    layout.setLabelWidth(130);
	    layout.setDefaultWidth(200);
	    setLayout(layout);
	    
	    setButtonAlign(HorizontalAlignment.CENTER);
	    setButtons(Dialog.OKCANCEL);
	    
	    setIcon(IconHelper.createStyle("user"));
	    setModal(true);
	    setBodyBorder(true);
	    setBodyStyle("padding: 8px;background: none");
	    setWidth(400);
	    setResizable(false);
	    initComponents();
	}
	
	private void initComponents() {
	    combo1.setFieldLabel("Услуга");
	    combo1.setDisplayField("name");  
	    combo1.setWidth(150);  
	    combo1.setStore(getPriceStore());
	    combo1.setTypeAhead(true);  
	    combo1.setTriggerAction(TriggerAction.ALL);
	    combo1.addSelectionChangedListener(new SelectionChangedListener<BeanModel>() {

			@Override
			public void selectionChanged(SelectionChangedEvent<BeanModel> se) {
				if (se.getSelectedItem() != null) {
					float cost = ((PriceBean)se.getSelectedItem().getBean()).getCost();
					ProcedureDialog.this.cost.setValue(cost);
				}
			}
	    	
	    });
	    add(combo1);
	    
	    combo2.setFieldLabel("Клиент");
	    combo2.setDisplayField("surname");  
	    combo2.setWidth(150);  
	    combo2.setStore(getClientStore());
	    combo2.setTypeAhead(true);  
	    combo2.setTriggerAction(TriggerAction.ALL);
	    add(combo2);
	    
	    combo3.setFieldLabel("Мастер");
	    combo3.setDisplayField("surname");  
	    combo3.setWidth(150);  
	    combo3.setStore(getMasterStore());
	    combo3.setTypeAhead(true);  
	    combo3.setTriggerAction(TriggerAction.ALL);
	    add(combo3);
	    
	    desc.setFieldLabel("Описание");
	    add(desc);
	    
	    cost.setFieldLabel("Цена");
	    add(cost);    
	    
	    date.setFieldLabel("Дата");
	    add(date);
	    
	    Button ok = getButtonById(Dialog.OK);
		ok.setText("ОК");
		ok.addSelectionListener(new SelectionListener<ButtonEvent>() {

			@Override
			public void componentSelected(ButtonEvent ce) {
				if (!getData()) {
					return;
				}
				((GreetingServiceAsync) Registry.get(Salon.SERVICE)).
				addProcedure(bean, new AsyncCallback<ProcedureBean>() {

					@Override
					public void onFailure(Throwable caught) {
						Info.display("Не удалось", "Добавить процедуру");
						
					}

					@Override
					public void onSuccess(ProcedureBean result) {
						Info.display("Добавление процедуры", "Успешно");
						ProcedureDialog.this.hide();
						if (ProcedureDialog.this.parentPanel != null)
							ProcedureDialog.this.parentPanel.refreshStore();
					}
					
				});
			}
			
		});
		
	    Button cancel = getButtonById(Dialog.CANCEL);
	    cancel.setText("Отмена");
	    cancel.addSelectionListener(new SelectionListener<ButtonEvent>() {

			@Override
			public void componentSelected(ButtonEvent ce) {
				ProcedureDialog.this.hide();
				
			}
	    });
	}
	private ListStore<BeanModel> getPriceStore() {
		RpcProxy<ListLoadResult<PriceBean>> empProxy = new RpcProxy<ListLoadResult<PriceBean>>() {
			@Override
			protected void load(Object loadConfig,
					final AsyncCallback<ListLoadResult<PriceBean>> callback) {
				((GreetingServiceAsync) Registry.get(Salon.SERVICE)).
				getPrice(0, 1000, null, new AsyncCallback<ParentPagingLoadResult<PriceBean>>() {
		
				public void onFailure(Throwable caught) {
					callback.onFailure(caught);
				}
		
				public void onSuccess(ParentPagingLoadResult<PriceBean> result) {
					callback.onSuccess(new BaseListLoadResult<PriceBean>(result.getData()));
				}});
			}
		};
		BaseListLoader<ListLoadResult<PriceBean>> empLoader = new BaseListLoader<ListLoadResult<PriceBean>>(empProxy, new BeanModelReader());   
		ListStore<BeanModel> empStore = new ListStore<BeanModel>(empLoader) {
			protected void onLoadException(LoadEvent le) {
				Info.display("Ошибка загрузки услуги", "{0}",
						le.exception.getMessage());
			}
		};
		empLoader.load();
		return empStore;
	}
	
	private ListStore<BeanModel> getClientStore() {
		RpcProxy<ListLoadResult<ClientBean>> empProxy = new RpcProxy<ListLoadResult<ClientBean>>() {
			@Override
			protected void load(Object loadConfig,
					final AsyncCallback<ListLoadResult<ClientBean>> callback) {
				((GreetingServiceAsync) Registry.get(Salon.SERVICE)).
				getClients(0, 1000, null, new AsyncCallback<ParentPagingLoadResult<ClientBean>>() {
		
				public void onFailure(Throwable caught) {
					callback.onFailure(caught);
				}
		
				public void onSuccess(ParentPagingLoadResult<ClientBean> result) {
					callback.onSuccess(new BaseListLoadResult<ClientBean>(result.getData()));
				}});
			}
		};
		BaseListLoader<ListLoadResult<ClientBean>> empLoader = new BaseListLoader<ListLoadResult<ClientBean>>(empProxy, new BeanModelReader());   
		ListStore<BeanModel> empStore = new ListStore<BeanModel>(empLoader) {
			protected void onLoadException(LoadEvent le) {
				Info.display("Ошибка загрузки клиента", "{0}",
						le.exception.getMessage());
			}
		};
		empLoader.load();
		return empStore;
	}
	
	private ListStore<BeanModel> getMasterStore() {
		RpcProxy<ListLoadResult<MasterBean>> empProxy = new RpcProxy<ListLoadResult<MasterBean>>() {
			@Override
			protected void load(Object loadConfig,
					final AsyncCallback<ListLoadResult<MasterBean>> callback) {
				((GreetingServiceAsync) Registry.get(Salon.SERVICE)).
				getMasters(0, 1000, null, new AsyncCallback<ParentPagingLoadResult<MasterBean>>() {
		
				public void onFailure(Throwable caught) {
					callback.onFailure(caught);
				}
		
				public void onSuccess(ParentPagingLoadResult<MasterBean> result) {
					callback.onSuccess(new BaseListLoadResult<MasterBean>(result.getData()));
				}});
			}
		};
		BaseListLoader<ListLoadResult<MasterBean>> empLoader = new BaseListLoader<ListLoadResult<MasterBean>>(empProxy, new BeanModelReader());   
		ListStore<BeanModel> empStore = new ListStore<BeanModel>(empLoader) {
			protected void onLoadException(LoadEvent le) {
				Info.display("Ошибка загрузки услуги", "{0}",
						le.exception.getMessage());
			}
		};
		empLoader.load();
		return empStore;
	}
	
	private boolean getData() {
		if (combo1.getValue() != null) {
			PriceBean mat = combo1.getValue().getBean();
			bean.setPriceId(mat.getId());
		}
		else {
			Info.display("Выберите", "услугу");
			combo1.focus();
			return false;
		}
		
		if (combo2.getValue() != null) {
			ClientBean mat = combo2.getValue().getBean();
			bean.setClientId(mat.getId());
		}
		else {
			Info.display("Выберите", "клиента");
			combo2.focus();
			return false;
		}
		
		if (combo3.getValue() != null) {
			MasterBean mat = combo3.getValue().getBean();
			bean.setMasterId(mat.getId());
		}
		else {
			Info.display("Выберите", "работника");
			combo3.focus();
			return false;
		}
		
		bean.setDesc(desc.getValue());
		if (cost.getValue() != null) {
			bean.setCost(cost.getValue().floatValue());			
		}
		
		bean.setDate(date.getValue());
		return true;
	}
}
